"use strict";
	var TD = TD || {};

	//美林版ajax对应接口
	TD.ajax = function(pm, succback, errorback){
		$.ajax({
			type: pm.type || 'GET',
			url: pm.url,
			dataType: 'json',
			data: pm.data || '',
			success: function(data){
				if (data.status == 1) {
					succback && succback(data.data);
				}else {
					errorback && errorback(data.message);
				}
			},
			error: function(xhr, status, thrown){
				errorback && errorback('网络连接不稳定，请重试或刷新页面！');
			}
		});
	};

	/*data参数说明
	data = {
		title: string, 朋友圈标题，给朋友的描述
		desc: string, 给朋友的标题
		link: string, 链接
		img: string, 图标
		track: string, 分享数据上报地址,post {btn:'1'}朋友或{btn:'2'}朋友圈
	}
	*/
	TD.wxShare = function(data, callback){
		wx.onMenuShareTimeline({
		    title: data.title, // 分享标题
		    link: data.link, // 分享链接
		    imgUrl: data.img, // 分享图标
		    success: function () { 
				callback && callback();
		    	//上报朋友圈
		        TD.ajax({
					type: 'POST',
					url: data.track,
					data: {
						btn: '2'
					}
				}, function(data){
					console.log(data);
				});
		    },
		    cancel: function () { 
		        // 用户取消分享后执行的回调函数
		    }
		});
		wx.onMenuShareAppMessage({
		    title: data.title, // 分享标题
		    desc: data.desc, // 分享描述
		    link: data.link, // 分享链接
		    imgUrl: data.img, // 分享图标
		    success: function () { 
				callback && callback();
		        //上报朋友
		        TD.ajax({
					type: 'POST',
					url: data.track,
					data: {
						btn: '1'
					}
				}, function(data){
					console.log(data);
				});
		    },
		    cancel: function () { 
		        // 用户取消分享后执行的回调函数
		    }
		});
	};
	
	//初始化微信接口
	//注意，与微信标准data相比，这里多了data.share属性，对应的是初始化页面时有默认的分享数据
	TD.initWxApi = function(data, succback){
		wx.config({
		    debug: false, 
		    appId: data.appId, 
		    timestamp: data.timestamp, 
		    nonceStr: data.nonceStr, 
		    signature: data.signature,
		    jsApiList: [
				'onMenuShareTimeline', 
				'onMenuShareAppMessage', 
				'startRecord', 
				'stopRecord', 
				'onVoiceRecordEnd', 
				'playVoice', 
				'pauseVoice', 
				'stopVoice', 
				'onVoicePlayEnd', 
				'uploadVoice', 
				'downloadVoice',
				'chooseImage',
				'previewImage',
				'uploadImage',
				'downloadImage'
			] 
		});
		wx.ready(function(){
			TD.wxShare(data.share);
		});
	};
	
	//预加载资源方法
	/*
	param = {
		imgs: ['../img1.jpg', '../img2.jpg'],
		//暂无队列，以后可以加上
		ajaxs: [
			{
				url: 'xxx.html',
				type: 'POST',
				data: {},
				succback: function(data){
					console.log(data);
				}
			},
			{
				url: 'xxx.html'
			}
		]
		ajax: ['xxx.html', 'xxx2.html']
	}
	
	var x = new TD.preload(param);
	x.loading = function(p){
		console.log(p);
	}
	x.loaded = function(imgs){
		console.log('succback');
	}
	//默认只有ajax请求不成功才会触发
	x.fail = function(err){
		console.log(err.url);
		console.log(err.msg);
	}
	//启动
	x.init();
	*/
	TD.preload = function(pm){
		var that = this;
		
		//预定义回调
		this.loading = null;
		this.loaded = null;
		this.fail = null;
		
		//预定义全局变量
		var imgsLen = pm.imgs ? pm.imgs.length : 0;
		var ajaxLen = pm.ajaxs ? pm.ajaxs.length : 0;
		var totalLen = imgsLen + ajaxLen;
		var count = 0;
		var imgsBack = [];
		
		//加载图片
		var loadImg = function(){
			var imgSuccessFn = function(){
				count++;
				if (count == totalLen) {
					that.loading && that.loading(100);
					that.loaded && that.loaded(imgsBack);
				}else {
					that.loading && that.loading(Math.round(count/totalLen * 100));
				}
			};
			
			for (var i = 0; i < imgsLen; i++) {
				var img = new Image();
				img.onload = img.onerror = imgSuccessFn;
				img.src = pm.imgs[i];
				imgsBack.push(img);
			}
		};
		
		//加载ajax
		var loadAjax = function(){
			var isErr = false;
			pm.ajax.forEach(function(value){
				TD.ajax({
					url: value.url,
					type: value.type || 'GET',
					data: value.data || '',
				}, (function(v){
					return function(data){
						if (isErr) {
							return;
						}
						count++;
						if (count == totalLen) {
							that.loaded && that.loaded(imgsBack);
						}else {
							that.loading && that.loading(Math.round(count/totalLen * 100));
						}
						v.succback && v.succback(data);
					};
				})(value), (function(v){
					return function(msg){
						isErr = true;
						that.fail && that.fail({
							msg: msg,
							url: v.url
						});
					};
				})(value));
			});
		};
		
		//初始化
		this.init = function(){
			if (totalLen == 0) {
				this.loaded && this.loaded(pm);
				return;
			}
			
			imgsLen !== 0 && loadImg(); 
			ajaxLen !== 0 && loadAjax();
		};
	};

	//数字补位函数pad(100, 5) => '00100'
    TD.pad = (function() {
        var padLen = 5; //补位常数
        var tbl = [];
        return function(num, n) {
            n = n || padLen;
            var len = n-num.toString().length;
            if (len <= 0) return num;
            if (!tbl[len]) tbl[len] = (new Array(len+1)).join('0');
            return tbl[len] + num;
        }
    })();

    //加载单个动画帧
    /*
	dom使用规则：<div class="canvas" data-prefix="title_" data-keyTo="83"></div>
	data-prefix是文件名前缀，也是内存中图片数组的名字，如上例内存中名字是title
	data-keyTo图片命名从0开始，例子中83是最后一张，图片需要数字补齐如title_00083.png

	el：canvas容器，jq对象；
	pathPrefix：图片的url前缀，如'img/'
	pad：图片名序列号补位数，默认是5位，如83补位5就是00083；
	postfix: 图片后缀，默认是png；
	
	//图片已加载完成回调
	preloadImgs.onload = callback;

	//图片加载中回调
	preloadImgs.onloading = callback;
	callback = function(p){
		//p是图片加载百分数
	}

	//执行加载，应该要放到上面两个回调函数之后用
	preloadImgs.load();

	//所有已经成功加载的图片数组都被存到了TD.preloadImgs对象的buffer中，属性名就是文件前缀，如上例就是TD.preloadImgs.buffer.title
    */
    TD.preloadImgs = (function(){

        var fn = function(el, pathPrefix, pad, postfix){
            var that = this;
            var prefixName = el.attr('data-prefix');
            var keyTo = parseInt(el.attr('data-keyTo'));
            var keyList = [];
            var count = 0;
            pad = pad || 5;
            postfix = postfix || 'png';
            this.len = keyTo+1;
            var successFn = function(){
                count++;

                that.onloading && that.onloading(Math.floor(count/(keyTo + 1) * 100));

                if (count == keyTo+1) {
                    //把已经加载好的dom存入内存缓存中方便后续调用:TD.preloadImgs.home_title
                    TD.preloadImgs.buffer[prefixName.slice(0, prefixName.length-1)] = keyList;
                    that.onload && that.onload();
                }
            }

            //写的时候必须先绑定onload，否则有可能从缓存中读取的onload事件会被忽略
            this.onload = null;
            this.onloading = null;
            this.load = function(){
                //如果在内存中已经保存
				/*
                if (TD.preloadImgs.buffer[prefixName.slice(0, prefixName.length-1)]) {
                    for(var i = 0; i < keyTo+1; i++){
                        count++;
                        that.onloading && that.onloading(100);
                    }
                    that.onload && that.onload();
                    return;
                };
				*/

                for(var i = 0; i < keyTo+1; i++){
                    var img = new Image();
                    img.src = pathPrefix + prefixName + TD.pad(i, pad) + '.' + postfix;
                    img.onload = img.onerror = successFn;
                    keyList.push(img);
                }
            }

        }
        //把函数当对象使用，存东西
        fn.buffer = {};
        return fn;
    })();
